﻿using System;
using System.Collections.Generic;
using UMC.Data;
using UMC.ITME.Entities;
using UMC.Net;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.ITME.Activities
{
    [Apiumc("ITME", "Alert", Auth = WebAuthType.Admin, Desc = "日志告警")]
    class SiteAlertActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            this.Context.Client.Context.NotCounted();
            var sId = this.AsyncDialog("Id", akey =>
             {

                 var alerts = DataFactory.Instance().Alert();//(new Net.StringValue(bytes));

                 var ui = UISection.Create(new UITitle("日志告警"));
                 if (alerts.Length > 0)
                 {
                     foreach (var a in alerts)
                     {
                         ui.AddCell(a.Title?.UTF8() ?? "新告警", new UIClick(request, akey, a.Id.ToString()));
                     }
                 }
                 else
                 {
                     UIDesc desc = new UIDesc("未配置告警");
                     desc.Desc("{icon}\n{desc}").Put("icon", "\uf24a");
                     desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                     ui.NewSection().Add(desc);
                 }
                 ui.UIFootBar = new UIFootBar() { IsFixed = true };
                 ui.UIFootBar.AddText(new UIEventText("新建告警").Click(new UIClick(request, akey, "0")),
                               new UIEventText("重新加载").Click(new UIClick(request, akey, "Reload")).Style(new UIStyle().BgColor()));


                 ui.SendTo(this.Context, $"{request.Model}.{request.Command},{request.Model}.{request.Command}.Del");


             });
            if (sId == "Reload")
            {
                HttpLogerDoWorker.ReloadAlert();
                this.Prompt("告警重新加载成功");
                return;
            }
            var id = UInt32.TryParse(sId, out var alertId) ? alertId : 0;

            var alert = alertId == 0 ? new Alert() : DataFactory.Instance().Alert(alertId);
            var model = alertId == 0 ? "Type" : this.AsyncDialog("model", r =>
            {
                if (alert != null)
                {
                    var ui = UISection.Create(new UITitle("日志告警"));
                    ui.Delete(UI.UI("告警标题", alert.Title?.UTF8(), new UIClick(request, r, "Title")), new UIEventText().Click(new UIClick(request, r, "Del")));
                    var value = alert.Value ?? StringValue.Empty;
                    switch (alert.Type)
                    {
                        case HttpLogerType.Error:
                            ui.AddCell("告警类型", "错误", new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Info:
                            ui.AddCell("告警类型", "信息", new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Alert:
                            ui.AddCell("告警类型", "警告", new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Debug:
                            ui.AddCell("告警类型", "调试", new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Host:
                            ui.AddCell("告警域名", value.UTF8(), new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Username:
                            ui.AddCell("告警用户", value.UTF8(), new UIClick(request, r, "Type"));
                            break;
                        case HttpLogerType.Duration:

                            ui.AddCell("告警耗时", $"{value.UTF8()}ms", new UIClick(request, r, "Type"));

                            break;
                        case HttpLogerType.Status:

                            ui.AddCell("告警状态", value.UTF8(), new UIClick(request, r, "Type"));

                            break;
                    }
                    var conUI = ui.NewSection();
                    var content = alert.Content ?? StringValue.Empty;//.UTF8();
                    if (content.IsEmpty)
                    {
                        UIDesc desc = new UIDesc("未有子项条件");
                        desc.Desc("{icon}\n{desc}").Put("icon", "\uf24a");
                        desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                        conUI.Add(desc);
                    }
                    else
                    {
                        var span = content.Span;

                        while (span.Length > 1)
                        {
                            var atype = (HttpLogerType)span[0];
                            var l = span[1];
                            switch (atype)
                            {
                                case HttpLogerType.Host:
                                    conUI.Delete(UI.UI("触发域名", span.Slice(2, l).UTF8()), new UIEventText().Click(new UIClick(request, r, "RemoveItem", "Type", "Host")));
                                    break;
                                case HttpLogerType.Path:
                                    conUI.Delete(UI.UI("触发路径", span.Slice(2, l).UTF8()), new UIEventText().Click(new UIClick(request, r, "RemoveItem", "Type", "Path")));
                                    break;
                                case HttpLogerType.Username:
                                    conUI.Delete(UI.UI("触发用户", span.Slice(2, l).UTF8()), new UIEventText().Click(new UIClick(request, r, "RemoveItem", "Type", "Username")));
                                    break;
                                case HttpLogerType.Duration:
                                    conUI.Delete(UI.UI("触发耗时", span.Slice(2, l).UTF8() + "ms"), new UIEventText().Click(new UIClick(request, r, "RemoveItem", "Type", "Duration")));
                                    break;
                                case HttpLogerType.Status:
                                    conUI.Delete(UI.UI("触发状态", span.Slice(2, l).UTF8()), new UIEventText().Click(new UIClick(request, r, "RemoveItem", "Type", "Status")));
                                    break;
                            }

                            span = span.Slice(l + 2);
                        }

                    }

                    ui.UIFootBar = new UIFootBar() { IsFixed = true };
                    ui.UIFootBar.AddText(new UIEventText("订阅此告警").Click(new UIClick(request, r, "Subscribe")),
                                  new UIEventText("新增子项条件").Click(new UIClick(request, r, "Item")).Style(new UIStyle().BgColor()));

                    ui.SendTo($"{request.Model}.{request.Command}.Del", this.Context, $"{request.Model}.{request.Command}");
                }
            });
            switch (model)
            {
                case "Subscribe":
                    {
                        var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];

                        var webr = new Uri(APIProxy.Uri, "Transfer").WebRequest();
                        UMC.ITME.Utility.Sign(webr, secret);

                        var data = JSON.Deserialize<WebMeta>(webr.Put(new WebMeta().Put("type", "Subscribe").Put("value", $"Alert/{alert.Id}"), out var xhr));
                        var ui = UISection.Create();
                        ui.Title = new UITitle("订阅告警提醒");

                        ui.Add(UICell.Create("QRCode", new WebMeta().Put("value", data["result"])));
                        var desc = new UIDesc(data["desc"] ?? "请用微信扫一扫完成模板消息订阅");
                        desc.Style.AlignCenter().Color(0x999).Padding(20, 20);
                        ui.Add(desc);
                        ui.SendTo(this.Context);
                    }
                    break;
                case "Title":
                    var title = this.AsyncDialog("Title", g => new UITextDialog()
                    {
                        Title = "告警标题",
                        DefaultValue = alert.Title?.UTF8()
                    });
                    DataFactory.Instance().Put(new Alert { Title = new StringValue(title), Id = alertId });
                    break;
                case "Del":
                    {
                        DataFactory.Instance().Delete(alert);
                        this.Context.Send($"{request.Model}.{request.Command}.Del", true);
                    }
                    break;
                case "RemoveItem":
                    {
                        var type3 = Utility.Parse(this.AsyncDialog("Type", g =>
                        {
                            var d = new UISheetDialog() { Title = "选择告警类型" };
                            d.Cells(4);
                            d.Put("错误", "Error").Put("信息", "Info").Put("警告", "Alert").Put("调试", "Debug").Put("耗时", "Duration").Put("状态", "Status").Put("域名", "Host").Put("用户", "Username");
                            return d;
                        }), HttpLogerType.Error);

                        var content = alert.Content ?? StringValue.Empty;
                        var maxValues = new byte[content.Length];
                        var valuesSpan = maxValues.AsSpan();
                        var span = content.Span;
                        while (span.Length > 1)
                        {
                            var atype = (HttpLogerType)span[0];
                            var l = span[1];
                            if (atype != type3)
                            {
                                span.Slice(0, l + 2).CopyTo(valuesSpan);
                                valuesSpan = valuesSpan.Slice(l + 2);//.ToArray();
                            }
                            span = span.Slice(l + 2);
                        }

                        DataFactory.Instance().Put(new Alert { Id = alertId, Content = new StringValue(maxValues, 0, maxValues.Length - valuesSpan.Length) });
                    }
                    break;
                case "Type":
                    var type = Utility.Parse(this.AsyncDialog("Type", g =>
                    {
                        var d = new UISheetDialog() { Title = "选择告警类型" };
                        d.Cells(4);
                        d.Put("错误", "Error").Put("信息", "Info").Put("警告", "Alert").Put("调试", "Debug").Put("耗时", "Duration").Put("状态", "Status").Put("域名", "Host").Put("用户", "Username");
                        return d;
                    }), HttpLogerType.Error);
                    if (alertId == 0)
                    {
                        alertId = Utility.TimeSpan();
                    }
                    switch (type)
                    {
                        case HttpLogerType.Info:
                        case HttpLogerType.Alert:
                        case HttpLogerType.Debug:
                        case HttpLogerType.Error:
                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId });//, type, "错误");
                            break;
                        case HttpLogerType.Host:
                            var host = this.AsyncDialog("Host", h => new UITextDialog() { Title = "域名", DefaultValue = alert.Value?.UTF8() });

                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId, Value = new StringValue(host) });//, type, "错误");
                            break;
                        case HttpLogerType.Path:
                            var Path = this.AsyncDialog("Path", h => new UITextDialog() { Title = "路径", DefaultValue = alert.Value?.UTF8() });
                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId, Value = new StringValue(Path) });

                            break;
                        case HttpLogerType.Username:
                            var Username = this.AsyncDialog("Username", h => new UITextDialog() { Title = "用户名", DefaultValue = alert.Value?.UTF8() });
                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId, Value = new StringValue(Username) });
                            break;
                        case HttpLogerType.Status:
                            var Status = this.AsyncDialog("Status", h => new UITextDialog(alert.Value?.UTF8()) { Title = "状态" });
                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId, Value = new StringValue(Status) });
                            break;
                        case HttpLogerType.Duration:
                            var Duration = this.AsyncDialog("Duration", h => new UINumberDialog(alert.Value?.UTF8()) { Title = "耗时" });
                            DataFactory.Instance().Put(new Alert { Type = type, Id = alertId, Value = new StringValue(Duration) });
                            break;

                    }
                    break;
                case "Item":
                    {
                        var type2 = this.AsyncDialog("Type", g =>
                       {
                           var d = new UIFormDialog() { Title = "新增子项条件" };
                           d.AddRadio("触发类型", "Type").Put("耗时", "Duration").Put("状态", "Status").Put("域名", "Host").Put("用户", "Username");
                           d.AddText("触发值", "Value");
                           return d;
                       });
                        var content = alert.Content ?? StringValue.Empty;
                        var logerType = Utility.Parse(type2["Type"], HttpLogerType.Host);
                        StringValue value = new StringValue(type2["Value"]);
                        var values = new byte[value.Length + 2];
                        values[0] = (byte)logerType;
                        values[1] = (byte)value.Length;
                        value.Span.CopyTo(values.AsSpan(2));
                        var maxValues = new byte[content.Length + values.Length];
                        var valuesSpan = maxValues.AsSpan();
                        var span = content.Span;
                        while (span.Length > 1)
                        {
                            var atype = (HttpLogerType)span[0];
                            var l = span[1];
                            if (atype != logerType)
                            {
                                span.Slice(0, l + 2).CopyTo(valuesSpan);
                                valuesSpan = valuesSpan.Slice(l + 2);//.ToArray();
                            }
                            span = span.Slice(l + 2);
                        }
                        values.CopyTo(valuesSpan);
                        valuesSpan = valuesSpan.Slice(values.Length);
                        DataFactory.Instance().Put(new Alert { Id = alertId, Content = new StringValue(maxValues, 0, maxValues.Length - valuesSpan.Length) });
                    }
                    break;
            }
            this.Context.Send(true);//new WebMeta().Put("type", alert.Type).Put("title", alert.Title).Put("value", alert.Value).Put("content", alert.Content), true);




        }

    }
}
